import { createStore } from 'vuex';
import axios from '../utils/axios'

const store = createStore({
  state() {
    return {
      // 购物车中商品的初始总数
      cartCount: null,
    }
  },
  mutations: {
    // 更新购物车中商品数据
    updateCartCount(state, count) {
      state.cartCount = count
    }
  },
  actions: {
    // 发送HTTP请求获取当前购物车中商品数据，借助数组的reduce方法累和，计算出已加购商品总数，更新cartCount
    fetchCartCount({ commit }) {
      axios.get('/inquire_shop').then((res) => {
        const cartGoodsCount = res.data.reduce((temp, item) => {
          return temp += item.number
        }, null)
        commit('updateCartCount', cartGoodsCount)
      })
    }
  }
})

export default store
